package qj.app.console.invoker;

import java.io.File;
import java.io.IOException;

import qj.app.console.Exec;
import qj.util.FileUtil;
import qj.util.IOUtil;
import qj.util.LangUtil;
import qj.util.ProcessUtil;
import qj.util.StringUtil;
import qj.util.SystemUtil;
import qj.util.funct.F0;
import qj.util.funct.P0;
import qj.util.funct.P1;

public class GaeInvoker extends AbstractInvoker {

	private F0<String> gaeHomeF = new F0<String>() {public String e() {
		return typeConfig.get("gae.home");
	}};
	private F0<String> appHomeF = new F0<String>() {public String e() {
		return config.get("war.home");
	}};
	private F0<Integer> portF = new F0<Integer>() {public Integer e() {
		String string = config.get("port");
		if (StringUtil.isEmpty(string)) {
			return null;
		} else {
			return Integer.parseInt(string);
		}
	}};
	
	public void start() {
		
		P1<String> normalOut = ta.createNormalOut();
		P1<String> errOut = ta.createErrOut();

		new File(gaeHomeF.e() + "/bin/wrapperCommands.txt").delete();
		
		ta.setText("");
		try {
			Integer port = portF.e();
			String cmd = "java -cp ../lib/appengine-tools-api.jar" + SystemUtil.classpathSeparator() + 
				SystemUtil.classPaths() + " " + Exec.class.getName() + 
				" com.google.appengine.tools.KickStart com.google.appengine.tools.development.DevAppServerMain --disable_update_check -a 0.0.0.0 " + 
				(port == null ? "" : "-p " + port + " ") +
				appHomeF.e();
//			System.out.println(cmd);
			process = Runtime.getRuntime().exec(
					cmd
					,null,new File(gaeHomeF.e() + "/bin"));
			
			IOUtil.readInputStreamToP1(process.getInputStream(), normalOut);
			IOUtil.readInputStreamToP1(process.getErrorStream(), errOut);
			
			onStart.e();
			ProcessUtil.onExit(process, new P0() {public void e() {
				onStop.e();
			}});
		} catch (IOException e1) {
			errOut.e(LangUtil.getStackTrace(e1));
		}
	}
	
	@Override
	public void stop() {
		FileUtil.writeToFile("exit", new File(gaeHomeF.e() + "/bin/wrapperCommands.txt"));
	}
	
//	JButton btnClean = btn("Clean", new P0() {public void e() {
//		new File(appHomeF.e() + "/WEB-INF/appengine-generated/local_db.bin").delete();
//	}});
}
